package com.caituo.idouyou.user.common.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.json.JSONException;
import org.json.JSONObject;

import com.opensymphony.xwork2.ActionContext;

public class HttpUtil {
	
	private static final Log log = LogFactory.getLog(HttpUtil.class);
	
	public static void retString(String str){
		ActionContext context = ActionContext.getContext();  
	    HttpServletRequest request = (HttpServletRequest) context.get(ServletActionContext.HTTP_REQUEST);  
	    HttpServletResponse response = (HttpServletResponse) context.get(ServletActionContext.HTTP_RESPONSE);  
		response.setContentType("application/json; charset=utf8");
		response.setStatus(HttpServletResponse.SC_OK);
		try {
			response.getWriter().println(str);
		} catch (IOException e) {
			log.error(e);
		}
		
	}
	
	
	public static void retError(HttpServletResponse response,String error){
		
		response.setContentType("text/xml; charset=utf8");
		response.setStatus(HttpServletResponse.SC_OK);
		try {
			response.getWriter().println("<response result='nok'>"+error+"</response>");
		} catch (IOException e) {
			log.error(e);
		}
		
	}
	public static void retError(HttpServletResponse response,String error,int errorcode){
		
		response.setContentType("text/xml; charset=utf8");
		response.setStatus(HttpServletResponse.SC_OK);
		try {
			response.getWriter().println("<response result='nok' errcode='"+errorcode+"' >"+error+"</response>");
		} catch (IOException e) {
			log.error(e);
		}
		
	}
	public static void retString(HttpServletResponse response,String res){
		
		response.setContentType("text/html; charset=utf8");
		response.setStatus(HttpServletResponse.SC_OK);
		try {
			response.getWriter().println(res);
		} catch (IOException e) {
			log.error(e);
		}		
	}
	public static void retString_(HttpServletResponse response,String res){
		
		response.setContentType("text/html; charset=utf-8");
		response.setStatus(HttpServletResponse.SC_OK);
		try {
			response.getWriter().print(res);
		} catch (IOException e) {
			log.error(e);
		}		
	}
	public static void retXmlString(HttpServletResponse response,String res){
		response.setContentType("text/xml; charset=utf8");
		response.setStatus(HttpServletResponse.SC_OK);
		try {
			System.out.println(res);
			response.getWriter().print(res);
		} catch (IOException e) {
			log.error(e);
		}	
	}
	public static void retOKString(HttpServletResponse response,String res){
		
		response.setContentType("text/xml; charset=utf8");
		response.setStatus(HttpServletResponse.SC_OK);
		try {
			response.getWriter().println("<response result='ok' >"+res+"</response>");
		} catch (IOException e) {
			log.error(e);
		}
		
	}
	
	public static void retJSONString(String str){
		ActionContext context = ActionContext.getContext();  
	    HttpServletResponse response = (HttpServletResponse) context.get(ServletActionContext.HTTP_RESPONSE);  
		response.setContentType("application/json;charset=utf8");
		response.setStatus(HttpServletResponse.SC_OK);
		try {
			response.getWriter().println(str);
		} catch (IOException e) {
			log.error(e);
		}
	}
	
	public static void retExceptionString(Exception e){
		try {
			ActionContext context = ActionContext.getContext();  
		    HttpServletResponse response = (HttpServletResponse) context.get(ServletActionContext.HTTP_RESPONSE);  
			response.setContentType("application/json;charset=utf8");
			response.setStatus(HttpServletResponse.SC_OK);
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("errorCode",ReturnCodeUtil.getCode(e.getMessage()));
			jsonObject.put("errorMsg", e.getMessage());
			response.getWriter().println(jsonObject.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		} catch (IOException e2) {
			e2.printStackTrace();
		}
	}
	
	public static String retExceptionString(String errorCode,String errorMsg){
		try {
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("errorcode",errorCode);
			jsonObject.put("errorMsg", errorMsg);
			return jsonObject.toString();
		} catch (JSONException e) {
			log.error(e);
		}
		return null;
		
	}
	
	public static String getAuthUser(HttpServletRequest request){
		 Cookie[] cookies = request.getCookies();  
	     if (cookies == null )
	     {
	    	 return null;
	     }
	     
	     if(cookies != null){
				for(Cookie cookie : cookies){

					if(cookie.getName().equals("auth")){
						String av=cookie.getValue();
						return av;
						}
					
					}
					
		}
		return null;
	     		
	}
	
	public static double getDistanceforLocation(double lat1, double lat2, double lon1,double lon2)
	{
		double radius=6371000;
		double distance=radius*Math.acos((Math.cos(lat2*Math.PI/180)*Math.cos(lat2*Math.PI/180)*Math.cos(lon1*Math.PI/180-lon2*Math.PI/180)+Math.sin(lat1*Math.PI/180)*Math.sin(lat2*Math.PI/180)));
		
		return distance;

	}
	public static Map<String, List<String>> getUrlParameters(String url)
	throws UnsupportedEncodingException {
		Map<String, List<String>> params = new HashMap<String, List<String>>();
		String[] urlParts = url.split("\\?");
		if (urlParts.length > 1) {
			String query = urlParts[1];
			for (String param : query.split("&")) {
				String pair[] = param.split("=");
				String key = URLDecoder.decode(pair[0], "UTF-8");
				String value = URLDecoder.decode(pair[1], "UTF-8");
				List<String> values = params.get(key);
				if (values == null) {
					values = new ArrayList<String>();
					params.put(key, values);
				}
				values.add(value);
			}
		}
		return params;
	}
	public static String FromSizeToStr(long Size) {
		String SizeStr = null;
		double SizeFloat = (double) Size;
		double KSize, MSize, GSize;
		KSize = SizeFloat / 1024;
		MSize = KSize / 1024;
		GSize = MSize / 1024;
		if (KSize < 1.0) {
			SizeStr = String.format("%dByte", Size);
			// sprintf(TxtBuf,"%ldByte",Size);
		} else if (MSize < 1.0) {
			long iInt, iFloat;
			iInt = (long) KSize;
			iFloat = (long) ((KSize - iInt) * 10);
			// if ((KSize - iInt) * 100 - iFloat >= 0.5)
			// iFloat++;
			// sprintf(TxtBuf,"%d.%02dKB", iInt, iFloat);
			SizeStr = String.format("%d.%01dKB", iInt, iFloat);
		} else if (GSize < 1.0) {
			long iInt, iFloat;
			iInt = (long) MSize;
			iFloat = (long) ((MSize - iInt) * 10);
			// if ((MSize - iInt) * 100 - iFloat >= 0.5)
			// iFloat++;
			// sprintf(TxtBuf,"%d.%02dMB", iInt, iFloat);
			SizeStr = String.format("%d.%01dMB", iInt, iFloat);

		} else {
			long iInt, iFloat;
			iInt = (long) GSize;
			iFloat = (long) ((GSize - iInt) * 10);
			// if ((GSize - iInt) * 100 - iFloat >= 0.5)
			// iFloat++;
			// sprintf(TxtBuf,"%d.%02dMB", iInt, iFloat);
			SizeStr = String.format("%d.%01dGB", iInt, iFloat);
		}
		return SizeStr;
	}
}
